<template>
  <ElFormItem
    :label="titleText(options, item)"
    :prop="[childIndex, 'value']"
    :rules="{
      required: item.isRequired === 'Y',
      message: '请上传',
      trigger: 'change',
    }"
    class="flex_column"
    list-type="picture-card"
  >
    <p v-if="options.showDesc" class="desc f12 mb10">
      {{ options.description }}
    </p>
    <ElUpload
      v-model:file-list="fileList"
      :accept="fileTypes"
      :auto-upload="false"
      :disabled="type === 'view'"
      :limit="options.limit || 1"
      :on-change="onChange"
      :on-exceed="onExceed"
      :on-preview="handlePictureCardPreview"
      :on-remove="beforeDelete"
      list-type="picture-card"
      placeholder="请选择"
    >
      <ElIcon>
        <Plus />
      </ElIcon>
    </ElUpload>
  </ElFormItem>
  <ElDialog v-model="dialogVisible">
    <ElImage :src="dialogImageUrl" alt="Preview Image" w-full />
  </ElDialog>
</template>

<script setup>
import { titleText } from "@/utils/common.js";
import { Plus } from "@element-plus/icons-vue";
import {
  ElDialog,
  ElFormItem,
  ElIcon,
  ElImage,
  ElMessage,
  ElUpload,
} from "element-plus";
import { ref, } from "vue";

//defineOptions({ name: "PCPictureUpload" });

const { item, type, index, childIndex } = defineProps([
  "item",
  "type",
  "index",
  "childIndex",
]);

const emits = defineEmits(["change"]);
const fileList = ref(item.value);
const { options } = JSON.parse(item.vformJson);
const fileTypes = [".jpg", ".jpeg", ".gif", ".png"];

// 文件变动
const onChange = (file, files) => {
  let type = file.name.split(".").pop().toLowerCase();
  if (fileTypes.indexOf("." + type) === -1) {
    ElMessage.error(`请上传 ${(fileTypes || []).join(",")} 格式图片`);
    let len = fileList.value.length - 1;
    fileList.value.splice(len, 1);
  } else {
    change(files);
  }
};
// 超出文件上传个数
const onExceed = () => {
  ElMessage.error("您最多可以上传" + options.limit + "张图片");
};
// 传递值改变后
const change = (files) => {
  item.value = files || fileList.value;
  emits("change", item);
};
// 删除
const beforeDelete = () => {
  change();
};
const dialogImageUrl = ref();
const dialogVisible = ref(false);
// 预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};
</script>